package org.demo.db.xsd;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.demo.xml.XmlTool;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * 工具类：类型映射工具 dbType -> xmlType
 * @author  
 * @date    2010-8-30
 * @file    org.gen.db.TypesMapTool.java
 */
public class TypesMapTool {
	/**
	 * dbType to xmlType
	 * @param dbType
	 * @return
	 */
	public static String getXmlType(String dbType){
		// 参数校验
		if (dbType == null){
			throw new RuntimeException("dbType must not be null.");
		}
		// get xmlType
		String xmlType = typesMap.get(dbType.toUpperCase());
		if (xmlType == null){
			xmlType = "xsd:string";
			System.out.println(":> not found xmlType by dbType=" + dbType);
		}
		return xmlType;
	}
	
	//---------------------------------------------------------------//
	// {"dbType":"xmlType",...}
	private static Map<String,String> typesMap = new HashMap<String,String>();
	static {
		try {
			// 初始化 typesMap
			InputStream is = TypesMapTool.class.getResourceAsStream("db.map.xml");
			// get root element
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(is);
			Element root = document.getDocumentElement();
			// get all type element
			List<Element> typeList = XmlTool.getChildren(root, "type");
			for (int i=0;i<typeList.size();i++){
				Element type = typeList.get(i);
				String dbType = type.getAttribute("dbType");
				String xmlType = type.getAttribute("xmlType");
				typesMap.put(dbType, xmlType);
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}
}
